package com.alpha.gateway.config;

import com.alpha.service.context.AlphaApplicationContext;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springdoc.core.GroupedOpenApi;
import org.springdoc.core.SwaggerUiConfigParameters;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.cloud.gateway.route.RouteDefinitionLocator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;

/**
 * open api 接口文档配置
 *
 * @author chenruwan
 * @since 2022-01-01
 */
@Slf4j
@Configuration
@RequiredArgsConstructor
public class GatewayOpenApiConfiguration {
    @Bean
    public List<GroupedOpenApi> groupedOpenApi(SwaggerUiConfigParameters swaggerParameters,
                                               RouteDefinitionLocator locator) {
        String applicationName = AlphaApplicationContext.getApplicationName();
        swaggerParameters.addGroup(applicationName);
        List<GroupedOpenApi> groups = List.of(GroupedOpenApi.builder()
                .pathsToMatch("/" + applicationName + "/**")
                .group(applicationName).build());

        List<RouteDefinition> definitions = locator.getRouteDefinitions().collectList().block();
        if (definitions == null) {
            return groups;
        }

        for (RouteDefinition definition : definitions) {
            log.info("definition id = {}, uri = {}", definition.getId(), definition.getUri().toString());
        }

        definitions.stream()
                // 网关自身服务已经添加到 swaggerParameters
                .filter(routeDefinition -> !routeDefinition.getUri().getAuthority().contains("localhost"))
                .forEach(routeDefinition -> {
                    String name = routeDefinition.getUri().getAuthority();
                    swaggerParameters.addGroup(name);
                });

        return groups;
    }
}
